(function () {

    var prizeList = document.querySelectorAll('.prize-list'),
        prizeNumber = document.querySelector('.prize-number'),
        dialogDom = document.querySelector('.dialog-container'),
        playBtn = document.querySelector('.handler-container-btn'),
        closeDom = document.querySelector('.close'),
        txtDom = document.querySelector('.dialog-main .content'),
        btnDom = document.querySelector('.dialog-main-footer .button'),
        num = 5, //抽奖次数
        index = -1, //当前选中的商品的下标
        current = null, //
        timerId = null, //定时器id
        duration = 50; //定时器时间


    function init() {
        prizeNumber.innerHTML = num
        initEvent()
    }

    function initEvent() {
        playBtn.addEventListener('click', playBtnFn)
        closeDom.addEventListener('click', closeBtnFn)
        btnDom.addEventListener('click', btnDomFn)
    }

    function btnDomFn() {
        
        if (num === 0) {
            dialogDom.style.display = 'none'
            return
        }
        dialogDom.style.display = 'none'
        prizeNumber.innerHTML = num
        runPlay()
    }

    function closeBtnFn() {
        
        dialogDom.style.display = 'none'
    }

    function playBtnFn() {
        if(num === 0 || timerId) return
        runPlay()
    }

    function openDialog() {

        
        dialogDom.style.display = 'block'
        var text = prizeList[current].querySelector('span').innerHTML
        console.log(text);
        if (current === 4) {
            txtDom.innerHTML = '再接再厉'
        } else {
            txtDom.innerHTML = '恭喜获得' + text
        }
        if (num === 0) {
            btnDom.innerHTML = '确定'
        }
    }

    function runPlay() {
        -- num
        prizeNumber.innerHTML = num
        var nums = 3000 + Math.floor(Math.random() * 2000)
        timerId = setInterval(() => {
            nums -= 200
            if (nums <= 200) {
                clearInterval(timerId)
                openDialog()
                return
            }
            current = ++index % prizeList.length
            prizeList.forEach(item => {
                item.classList.remove('active')
            })
            prizeList[current].classList.add('active')
        }, duration);
    }

    init()
})()